package com.gf.base.controller;

import java.sql.SQLException;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.mail.MailException;
import org.springframework.web.bind.annotation.ExceptionHandler;

import com.gf.common.constant.ViewPaths;
import com.gf.common.exception.BusinessException;
import com.gf.common.exception.NotLoginException;
import com.gf.common.exception.NotOperationEexception;
import com.sun.mail.smtp.SMTPAddressFailedException;

/**
 * 处理异常 如：没有登入的情况
 * 
 * @author Colonel
 * 
 */
public class BasicController {

	private Log logger = LogFactory.getLog(BasicController.class);

	// 对业务异常进行处理
	@ExceptionHandler(BusinessException.class)
	protected String handlerBussinessExceptions(HttpServletRequest request,
			BusinessException ex) {
		if (ex instanceof NotLoginException) {
			logger.warn("异常:用户没有登入");
			return "redirect:" + ViewPaths.LOGIN_VIEW + ViewPaths.SUFFIX;
		} else if (ex instanceof NotOperationEexception) {
			logger.warn("异常：你没有权限进行操作");
			return "redirect:" + ViewPaths.LOGIN_VIEW + ViewPaths.SUFFIX;
		} else {
			logger.error("异常:业务出现错误。");
			return "redirect:" + ViewPaths.LOGIN_VIEW + ViewPaths.SUFFIX;
		}

	}

	@ExceptionHandler(Exception.class)
	protected String handlerException(HttpServletRequest request, Exception ex) {
		if (ex instanceof MailException) {
			logger.warn("异常:邮件发送错误。");
		} else if (ex instanceof SMTPAddressFailedException) {
			logger.warn("异常:邮件发送错误。不存在该邮箱");
		}

		else if (ex instanceof SQLException) {
			logger.warn("异常:sql 出错");
		}

		logger.error("异常:业务出现错误。");
		return "error";
	}

}
